<?
/*
		topGames: an iRC games bot
		Copyright (C) 2008 Marcos Garc�a <marcosgdf@gmail.com>
    
		This file is part of topGames

		This program is free software: you can redistribute it and/or modify
		it under the terms of the GNU General Public License as published by
		the Free Software Foundation, either version 3 of the License, or
		any later version.

		This program is distributed in the hope that it will be useful,
		but WITHOUT ANY WARRANTY; without even the implied warranty of
		MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
		GNU General Public License for more details.

		You should have received a copy of the GNU General Public License
		along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
define('LOGO','12[t14G]');
define('FULL_LOGO','12[top14Games]');
$_TEMP = array();

function initFunction($tg) {
	$pid = getmypid();
	$tg->dbSend("UPDATE ".DB_PREFIX."autojoin SET `is_in`='0' WHERE `is_in`='1' AND `bot_number`='".BOT_NUMBER."'");
	$tg->dbSend("DELETE FROM ".DB_PREFIX."channelusers WHERE `bot_number`='".BOT_NUMBER."'");
	$tg->dbSend("UPDATE ".DB_PREFIX."settings SET `valor`='".time()."' WHERE `campo`='uptime_".BOT_NUMBER."'");
	$tg->dbSend("UPDATE ".DB_PREFIX."settings SET `valor`='$pid' WHERE `campo`='pid_".BOT_NUMBER."'");
	$tg->ctime = time();
	$query = $tg->dbSend("SELECT `valor` FROM ".DB_PREFIX."settings WHERE `campo`='portero'");
	$result = @mysql_result($query, 0);
	if (!$result) $tg->portero = 'topGames'; else $tg->portero = $result;
}
function loop($tg,$sockfd) {
	$tg->dbConnect(); //starts a persistant mysql connection
	$tg->dbSelect(); //selects the DB we are going to use
	initFunction($tg); //updates some tables of the BD
	$tg->ircIdentify(); //send some params to the iRC server
	while (!feof($sockfd)) process($tg,$sockfd,fgets($sockfd,2048)); //makes a loop to the process function
}

function initConnect($tg) {
	echo "[+] conectando...\n";
	$tg->ircConnect(); //opens an iRC connection
	loop($tg,$tg->sockfd); //starts loop function with the socket of the iRC connection
}

function process($tg,$sockfd,$data) {
	$tmp_msg = str_replace("\n","", str_replace("\r","",$data)); //remove \n and \r characters
	$split_msg = explode(" ",$tmp_msg); //splits $tmp_msg in an array
	if (IRC_DEBUG) echo $data; //makes a debug of the iRC connection
	if (PING_SERVER) {
		if (!$tg->ping) {
			$tg->ping = time();
			$tg->doPing();
		}
		else {
			$difference = time() - $tg->ping;
			if ($difference >= PING_FREQUENCY) $tg->doPing();
		}
	}
	if (is_array($split_msg) && (count($split_msg) > 1)) {
		if ($split_msg[0] == "PING") { //if the server makes a ping, reply with pong
			$tg->ircSend(sprintf("PONG :%s \r\n",str_replace(":","", $split_msg[1])));
			if (!$tg->isIrcConnected()) { //continue if it's our first ping
				global $_CFG;
				$tg->changeIrcStatus(true);
				$message = "Conectado a ".IRC_SERVER;
				if (LOG_STATUS && (in_array('status',$_CFG["LOG_REC"]))) $tg->writeLog($message);
				echo "[+] $message\n";
				set_time_limit(0); //modifies the timeout to 0
				if (!empty($_CFG["CMD_AFTER_CONNECT"])) eval($_CFG["CMD_AFTER_CONNECT"]); //if $_CFG["CMD_FTER_CONNECT"] param is set, evaluates the code
				$tg->joinChannel(CHANNEL); //join the official channel
				$query = $tg->dbSend("SELECT valor FROM ".DB_PREFIX."settings WHERE `campo`='ajoin'");
				if ($query) { //checks if the query was correct
					$result = mysql_result($query,0); //exports the query data to the variable
					if ($result == 1) { //continues if ajoin option is activated
						$allChannelsOut = $tg->getChannels(0); //checks the number of the channels 
						if ($allChannelsOut >= 1) {
							$tg->ircMsg(CHANNEL,'Iniciando el proceso de autojoin... (esto puede durar unos minutos)', true);
							if (LOG_STATUS && (in_array('status',$_CFG["LOG_REC"]))) $tg->writeLog("Iniciando el proceso de autojoin"); //if the bot is said to log the status issues, it will record them
							$allChannels = $tg->getAutojoin(); //loads all the channels
							$stringChannels = '';
							foreach ($allChannelsOut AS $channel) {
								$tg->joinChannel($channel); //joins the channel
								$stringChannels .= $channel.' ';
							}
							$tg->ircMsg(CHANNEL,"He entrado en ".$tg->h(' '.count($allChannelsOut))." canales:".$tg->h($stringChannels), true);
							if (LOG_STATUS && (in_array('status',$_CFG["LOG_REC"]))) $tg->writeLog("Ajoin finalizado. Se ha entrado en ".count($allChannelsOut).' canales');
						}
					}
				}
				else {
				    $message = 'Error al obtener las preferencias del ajoin';
    				if (LOG_STATUS && (in_array('status',$_CFG["LOG_REC"]))) $tg->writeLog($message);
    				echo "[-] $message\n";
                }
			}
		}
		if (is_numeric($split_msg[1])) { //if first param is a raw, send to raw class
			$raw = new raw;
			$raw->action($tg,$tmp_msg);
		}
		else {
			if ($split_msg[1] == "PRIVMSG") {
				if (strpos($split_msg[2],"#") !== false) { //continue if there are messages from a channel
					$tmpc = array();
					for ($i=3;$i < count($split_msg);$i++) $tmpc[] = $split_msg[$i];
					$nick = explode("!", $split_msg[0]);
					$nick = str_replace(":", "", $nick[0]);
					if (eregi(CHANNEL,$split_msg[2])) {
						$bot = new bot;
						$bot->action($tg,$tmpc,$nick);
					}
					else {
						if ($nick != IRC_NICK) { //if the channel is different of the official channel, it sends to class juegos
							$juegos = new juegos;
							$juegos->action($tg,$nick,$split_msg[2],$tmpc);
						}
					}
				}
			}
			else { 
				$events = new events;
				$events->action($tg,$split_msg);
			}
		}
	}
}
?>